package com.zdkj.subway.st.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.annotation.Inner;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.st.constant.enums.TicketRecycleDeliveryEnum;
import com.zdkj.subway.st.dto.in.SwTkTemporaryDistributionPlanNoticeDTO;
import com.zdkj.subway.st.dto.in.SwTkTicketDeliveryDTO;
import com.zdkj.subway.st.dto.in.SwTkTicketDeliveryDetailEditDTO;
import com.zdkj.subway.st.dto.in.SwTkTicketDeliveryEditDTO;
import com.zdkj.subway.st.dto.out.SwTkTicketDeliveryExportDTO;
import com.zdkj.subway.st.dvo.SwTkTicketDeliveryAndDetailExcelDvo;
import com.zdkj.subway.st.entity.*;
import com.zdkj.subway.st.mapper.SwParamLineMapper;
import com.zdkj.subway.st.mapper.SwParamStationMapper;
import com.zdkj.subway.st.mapper.SwTkTicketDeliveryMapper;
import com.zdkj.subway.st.service.*;
import com.zdkj.subway.st.util.DateUtilsSt;
import com.zdkj.subway.st.util.LocalDateConverter;
import com.zdkj.subway.st.util.LocalDateTimeConverter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 车票配送(线网)/配入(车站)主表
 * 此功能对应 SwStTicketHandController
 *
 * @author cuilei
 * @date 2020-06-12 17:39:25
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/swtkticketdelivery")
@Api(value = "swtkticketdelivery", tags = "车票配送(线网)/配入(车站)主表管理")
public class SwTkTicketDeliveryController {
    private static final Logger LOGGER = LoggerFactory.getLogger(SwTkTicketDelivery.class);
    private final SwTkTicketDeliveryService swTkTicketDeliveryService;
    private final SwTkTicketDeliveryDetailService swTkTicketDeliveryDetailService;
    private final SwTkTemporaryDistributionPlanNoticeService swTkTemporaryDistributionPlanNoticeService;
    @Resource
    SwTkTicketDeliveryMapper swTkTicketDeliveryMapper;
    @Resource
    private SwParamLineMapper swParamLineMapper;
    @Resource
    private SwParamStationMapper swParamStationMapper;
    @Resource
    private final SwPmTicketCardTypeService swPmTicketCardTypeService;
    @Resource
    private final SwPmTicketCardTypeParamService swPmTicketCardTypeParamService;

    /**
     * 分页查询
     *
     * @param page               分页对象
     * @param swTkTicketDelivery 车票配送/配入主表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping({"/page", "/station/page"})
    public R getSwTkTicketDeliveryPage(Page page, SwTkTicketDelivery swTkTicketDelivery) {
        PigxUser user = SecurityUtils.getUser();
        //String dateCondition = swTkTicketDelivery.getDeliveryTimeDTO();
        QueryWrapper<SwTkTicketDelivery> lambdaQueryWrapper = Wrappers.query(swTkTicketDelivery);
		lambdaQueryWrapper.orderByAsc("LINE_CODE");
		lambdaQueryWrapper.orderByAsc("STATION_CODE");
        lambdaQueryWrapper.orderByDesc("DELIVERY_TIME","RECEIVE_TIME");
        //LambdaQueryWrapper<SwTkTicketDelivery> lambdaQueryWrapper = Wrappers.query(swTkTicketDelivery).lambda();
        /*if (StringUtils.isNotBlank(dateCondition)) {
            lambdaQueryWrapper.lambda().likeRight(SwTkTicketDelivery::getDeliveryTime, dateCondition);
        }*/
        //售卖时间
        List<String> dateCondition = swTkTicketDelivery.getDates1();
        List<String> dateConditionhs2 = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(swTkTicketDelivery.getDates2())){
            if(swTkTicketDelivery.getDates2().get(0)!=null&&!"".equals(swTkTicketDelivery.getDates2().get(0))){
                dateConditionhs2 = swTkTicketDelivery.getDates2();
            }
        }
        if (ObjectUtil.isNotEmpty(dateCondition)) {
            lambdaQueryWrapper.lambda().apply("DATE_FORMAT(DELIVERY_TIME,'%Y-%m-%d') between DATE_FORMAT('"+dateCondition.get(0)+"','%Y-%m-%d') and DATE_FORMAT('"+dateCondition.get(1)+"','%Y-%m-%d')");
        }
        if (ObjectUtil.isNotEmpty(dateConditionhs2)) {
            lambdaQueryWrapper.lambda().apply("DATE_FORMAT(RECEIVE_TIME,'%Y-%m-%d') between DATE_FORMAT('"+dateConditionhs2.get(0)+"','%Y-%m-%d') and DATE_FORMAT('"+dateConditionhs2.get(1)+"','%Y-%m-%d')");
        }
        if (!user.getBelongToLine()) {
            //获取通知状态是已通知
            return R.ok(swTkTicketDeliveryService.page(page, lambdaQueryWrapper.lambda()
                    .eq(SwTkTicketDelivery::getNoticeStatus, CommonConstants.INFORMED)
                    .eq(SwTkTicketDelivery::getLineCode, user.getLineCode())
                    .eq(SwTkTicketDelivery::getStationCode, user.getStationCode())));
        } else {
            return R.ok(swTkTicketDeliveryService.page(page, lambdaQueryWrapper));
        }
    }

    /**
     * 通过id查询车票配送/配入主表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping({"/{id}", "/station/{id}"})
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swTkTicketDeliveryService.getById(id));
    }

    /**
     * 通过id查询车票配送/配入主表及明细
     *
     * @param id idswtkticketdelivery
     * @return R
     */
    @ApiOperation(value = "通过id查询车票配送/配入主表及明细", notes = "通过id查询车票配送/配入主表及明细")
    @GetMapping({"/getDetailById/{id}", "/station/getDetailById/{id}"})
    public R getDetailById(@PathVariable("id") Integer id) {
        return R.ok(swTkTicketDeliveryService.getDetailById(id));
    }

    /**
     * 线网新增车票配送及明细
     *
     * @param swTkTicketDelivery 车票配送/配入及明细
     * @return R
     */
    @ApiOperation(value = "线网新增车票配送及明细", notes = "线网新增车票配送及明细")
    @SysLog("线网新增车票配送及明细")
    @PostMapping()
    @PreAuthorize("@pms.hasPermission('st_sw_tk_ticket_delivery_add')")
    public R save(@RequestBody SwTkTicketDeliveryDTO swTkTicketDelivery) {
        SwTkTicketDelivery defaultObj = ObjectUtils.getDefaultObj(SwTkTicketDelivery.class);
        BeanUtils.copyProperties(swTkTicketDelivery, defaultObj);

        List<SwTkTicketDeliveryDetail> swTkTicketDeliveryDetails = swTkTicketDelivery
                .getSwTkTicketDeliveryDetails();
        int totalCount = swTkTicketDeliveryDetails.stream()
                .mapToInt(SwTkTicketDeliveryDetail::getDeliveryCount).sum();
        defaultObj.setDeliveryCount(totalCount);
        swTkTicketDeliveryService.save(defaultObj);

        swTkTicketDeliveryDetails.forEach(item -> item.setRefId(defaultObj.getId()));
        return R.ok(swTkTicketDeliveryDetailService.saveBatch(swTkTicketDeliveryDetails));
    }

    /**
     * 修改车票配送/配入主表及明细
     *
     * @param swTkTicketDelivery 车票配送/配入主表及明细
     * @return R
     */
    @ApiOperation(value = "车票配送与回收功能修改", notes = "修改车票配送/配入主表及明细")
    @SysLog("修改车票配送/配入主表及明细")
    @PutMapping()
    @PreAuthorize("@pms.hasPermission('st_sw_tk_ticket_delivery_edit')")
    @Transactional
    public R updateByDeliveryId(@RequestBody SwTkTicketDeliveryDTO swTkTicketDelivery) {
        SwTkTicketDelivery updateObj = new SwTkTicketDelivery();
        BeanUtils.copyProperties(swTkTicketDelivery, updateObj);
        int totalCount = swTkTicketDelivery.getSwTkTicketDeliveryDetails().stream()
                .mapToInt(SwTkTicketDeliveryDetail::getDeliveryCount).sum();
        updateObj.setDeliveryCount(totalCount);
        swTkTicketDeliveryService.updateById(updateObj);

        //先删除之前旧的子表数据
        swTkTicketDeliveryDetailService.deleteByRefId(updateObj.getId());

        List<SwTkTicketDeliveryDetail> listDetail = swTkTicketDelivery.getSwTkTicketDeliveryDetails();
        listDetail.forEach(item -> item.setRefId(updateObj.getId()));
        swTkTicketDeliveryDetailService.saveBatch(listDetail);
        return R.ok();
    }


    /**
     * 通过ids删除车票配送
     *
     * @param ids id
     * @return R
     */
    @ApiOperation(value = "通过ids删除车票配送", notes = "通过ids删除车票配送")
    @SysLog("通过ids删除车票配送")
    @DeleteMapping("/delBatch")
    @PreAuthorize("@pms.hasPermission('st_sw_tk_ticket_delivery_delBatch')")
    public R delBatch(@RequestBody List<Integer> ids) {
        return R.ok(swTkTicketDeliveryService.removeByIds(ids));
    }


    /**
     * 导出车票配送信息
     *
     * @param swTkTicketDelivery
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "导出车票配送信息", notes = "导出车票配送信息")
    @GetMapping("/export")
    @SysLog("导出车票配送信息")
    @PreAuthorize("@pms.hasPermission('st_sw_tk_ticket_delivery_export')")
    public void exportExcel(SwTkTicketDelivery swTkTicketDelivery, HttpServletResponse response) throws IOException {
        List<SwTkTicketDelivery> swStTicketTestReceivelist = swTkTicketDeliveryService.list(Wrappers.query(swTkTicketDelivery));
        String fileName = URLEncoder.encode("车票配送", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SwTkTicketDelivery.class).registerConverter(new LocalDateTimeConverter())
                .registerConverter(new LocalDateConverter()).sheet("车票配送").doWrite(swStTicketTestReceivelist);
    }

    /**
     * 导出车票配入信息
     *
     * @param ids
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "导出车票配入信息", notes = "导出车票配入信息")
    @GetMapping("/pr_export")
    @SysLog("导出车票配入信息")
    //@PreAuthorize("@pms.hasPermission('st_sw_tk_ticket_delivery_pr_export')")
    public void exportPrExcel(@RequestParam(value = "ids") List<Integer> ids, HttpServletResponse response) throws IOException {
        List<SwTkTicketDeliveryExportDTO> list = new ArrayList<>();
        PigxUser user = SecurityUtils.getUser();
        Map<String,String> params = new HashMap<>();
        params.put("lineCode",user.getLineCode());
        params.put("stationCode",user.getStationCode());
        List<SwTkTicketDelivery> swStTicketTestReceivelist = swTkTicketDeliveryMapper.queryExport(ids,params);
        swStTicketTestReceivelist.forEach(i -> {
            if(i.getDeliveryStatus().equals("0")){
                i.setDeliveryStatus("待确认");
            }else if(i.getDeliveryStatus().equals("1")){
                i.setDeliveryStatus("已确认");
            }else if(i.getDeliveryStatus().equals("2")){
                i.setDeliveryStatus("差异反馈");
            }else{
                i.setDeliveryStatus("差异申诉");
            }
            SwTkTicketDeliveryExportDTO dto = new SwTkTicketDeliveryExportDTO();
            BeanUtils.copyProperties(i, dto);
            list.add(dto);
        });
        String fileName = URLEncoder.encode("车票配入", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SwTkTicketDeliveryExportDTO.class).registerConverter(new LocalDateTimeConverter())
                .registerConverter(new LocalDateConverter()).sheet("车票配入").doWrite(list);
    }


    /**
     * 线网车票配送通知
     *
     * @param listIds 配送的主表ID
     * @return
     */
    @ApiOperation(value = "线网车票配送通知", notes = "线网车票配送通知")
    @SysLog("线网车票配送通知")
    @PostMapping("/inform")
    @Transactional
    public R inform(@RequestBody List<Integer> listIds) {
        List<SwTkTemporaryDistributionPlanNoticeDTO> informList = new ArrayList<>();
        List<SwTkTicketDelivery> listSwTkTicketDelivery = new ArrayList<>();
        listIds.forEach(item -> {
            SwTkTicketDelivery dbDelivery = swTkTicketDeliveryService.getById(item);
            //先添加通知表数据
            SwTkTemporaryDistributionPlanNoticeDTO informItem = new SwTkTemporaryDistributionPlanNoticeDTO();
            informItem.setRefId(dbDelivery.getId());
            informItem.setLineCode(dbDelivery.getLineCode());
            informItem.setStationCode(dbDelivery.getStationCode());
            informItem.setDistributionNumber(dbDelivery.getDeliveryCount());
            informItem.setDistributionPersonName(dbDelivery.getDeliveryPersonName());
            informItem.setDistributionPersonCode(dbDelivery.getDeliveryPersonCode());
            informItem.setDistributionTime(dbDelivery.getDeliveryTime());
            informItem.setDistributionType(TicketRecycleDeliveryEnum.DELIVERY.getCode());
            informList.add(informItem);

            //再更改通知状态
            dbDelivery.setNoticeStatus(CommonConstants.INFORMED);
            listSwTkTicketDelivery.add(dbDelivery);
        });
        swTkTemporaryDistributionPlanNoticeService.saveBathByNotice(informList);
        return R.ok(swTkTicketDeliveryService.updateBatchById(listSwTkTicketDelivery));
    }

    @PutMapping("/inputDetailSubmit")
    @SysLog("加入车票入库")
    public R inputDetailSubmit(@Valid @RequestBody List<Integer> ids) {
        return R.ok(swTkTicketDeliveryService.inputDetailSubmitBatch(ids));
    }

    @PutMapping("/outputDetailSubmit")
    @SysLog("加入车票出库")
    public R outputDetailSubmit(@Valid @RequestBody List<Integer> ids) {
        return R.ok(swTkTicketDeliveryService.outputDetailSubmitBatch(ids));
    }

    /**
     * 车站车票配入确认并反馈
     *
     * @param swTkTicketDelivery
     * @return
     */
    @ApiOperation(value = "车站车票配入确认并反馈", notes = "车站车票配入确认并反馈")
    @SysLog("车站车票配入确认并反馈")
    @PostMapping("/station/confirmOrFeedBack")
    public R confirmOrFeedback(@RequestBody SwTkTicketDeliveryEditDTO swTkTicketDelivery) {
        SwTkTicketDelivery confirm = new SwTkTicketDelivery();
        BeanUtils.copyProperties(swTkTicketDelivery, confirm);
        confirm.setDeliveryStatus(TicketRecycleDeliveryEnum.CONFIRM.getCode());
        if (StringUtils.isNotBlank(swTkTicketDelivery.getFeedback())) {
            confirm.setFeedback(swTkTicketDelivery.getFeedback());
            confirm.setDeliveryStatus(TicketRecycleDeliveryEnum.FEEDBACK.getCode());
        }
        //更新子表和主表的接收数量和差异数量
        List<SwTkTicketDeliveryDetailEditDTO> listDetail = swTkTicketDelivery.getSwTkTicketDeliveryDetails();
        listDetail.forEach(item -> {
            SwTkTicketDeliveryDetail detail = swTkTicketDeliveryDetailService.getById(item.getId());
            BeanUtils.copyProperties(item, detail);
            swTkTicketDeliveryDetailService.updateById(detail);
            if(detail.getReceiveCount() != null || detail.getReceiveCount() != 0){
                if(confirm.getReceiveCount()==null){
                    int receiveCount = 0;
                    int differenceCount = 0;
                    confirm.setReceiveCount(receiveCount+detail.getReceiveCount());
                    confirm.setDifferenceCount(differenceCount+detail.getDifferenceCount());
                }else {
                    confirm.setReceiveCount(confirm.getReceiveCount()+detail.getReceiveCount());
                    confirm.setDifferenceCount(confirm.getDifferenceCount()+detail.getDifferenceCount());
                }
            }

        });
        return R.ok(swTkTicketDeliveryService.updateById(confirm));
    }

    @ApiOperation(value = "车站车票配入三天自动确认", notes = "车站车票配入三天自动确认")
    @Inner
    @PostMapping("/station/autoConfirm")
    public R confirm() {
        //查找已通知，主表没确认，且配入状态也没有确认的数据,查找当前时间三天前的数据。
        List<SwTkTicketDelivery> list = swTkTicketDeliveryService.list(Wrappers.<SwTkTicketDelivery>query().lambda()
                .eq(SwTkTicketDelivery::getNoticeStatus, CommonConstants.INFORMED)
                .eq(SwTkTicketDelivery::getNoticeConfirm, CommonConstants.UN_CONFIRM)
                .eq(SwTkTicketDelivery::getDeliveryStatus, TicketRecycleDeliveryEnum.UN_CONFIRM.getCode())
                .le(SwTkTicketDelivery::getDeliveryTime, DateUtilsSt.getPreDayDateTime(3)));
        list.forEach(delivery -> {
            //设置为主表已确认，子表
            delivery.setNoticeConfirm(CommonConstants.CONFIRM);
            swTkTicketDeliveryService.updateById(delivery);

            List<SwTkTicketDeliveryDetail> listDetail = swTkTicketDeliveryDetailService.list(Wrappers
                    .<SwTkTicketDeliveryDetail>query().lambda()
                    .eq(SwTkTicketDeliveryDetail::getRefId, delivery.getId()));
            listDetail.forEach(item -> {
                //更新子表的接收数量为配送数量和差异数量为0
                item.setReceiveCount(item.getDeliveryCount());
                item.setDifferenceCount(0);
            });
            if (!listDetail.isEmpty()) {
                swTkTicketDeliveryDetailService.updateBatchById(listDetail);
            }
        });
        return R.ok();
    }


    /**
     * 线网申诉车票配送差异
     *
     * @param swTkTicketDelivery
     * @return
     */
    @ApiOperation(value = "线网申诉车票配送差异", notes = "线网申诉车票配送差异")
    @SysLog("线网申诉车票配送差异")
    @PostMapping("/complain")
    public R complain(@RequestBody SwTkTicketDelivery swTkTicketDelivery) {
        SwTkTicketDelivery complain = new SwTkTicketDelivery();
        complain.setId(swTkTicketDelivery.getId());
        if (StringUtils.isNotBlank(swTkTicketDelivery.getComplain())) {
            complain.setComplain(swTkTicketDelivery.getComplain());
        }
        if (StringUtils.isNotBlank(swTkTicketDelivery.getLineSurveyResult())) {
            complain.setLineSurveyResult(swTkTicketDelivery.getLineSurveyResult());
        }
        complain.setDeliveryStatus(TicketRecycleDeliveryEnum.COMPLAIN.getCode());
        return R.ok(swTkTicketDeliveryService.updateById(complain));
    }

    /**
     * 通过id删除车票配送/配入主表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除车票配送/配入主表", notes = "通过id删除车票配送/配入主表")
    @SysLog("通过id删除车票配送/配入主表")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('st_sw_tk_ticket_delivery_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swTkTicketDeliveryService.removeById(id));
    }

    /**
     * 过期未确认自动确认任务
     *
     * @return
     */
    @Inner
    @ApiOperation(value = "过期未确认自动确认任务", notes = "过期未确认自动确认任务")
    @SysLog("过期未确认自动确认任务")
    @GetMapping("/task/confirmTask")
    public R confirmTask() {
        List<SwTkTicketDelivery> overTimeList = swTkTicketDeliveryService.getOverTimeList();
        overTimeList.forEach(item -> {
            List<SwTkTicketDeliveryDetail> overTimeDetailList = swTkTicketDeliveryDetailService
                    .list(Wrappers.<SwTkTicketDeliveryDetail>query().lambda()
                            .eq(SwTkTicketDeliveryDetail::getRefId, item.getId()));

            overTimeDetailList.forEach(detailItem -> {
                detailItem.setReceiveCount(detailItem.getDeliveryCount());
                detailItem.setDifferenceCount(0);
            });

            int totalReceiveCount = overTimeDetailList.stream()
                    .mapToInt(SwTkTicketDeliveryDetail::getReceiveCount).sum();
            int totalDiffCount = overTimeDetailList.stream()
                    .mapToInt(SwTkTicketDeliveryDetail::getDifferenceCount).sum();
            item.setReceiveCount(totalReceiveCount);
            item.setDifferenceCount(totalDiffCount);
            item.setReceiveTime(LocalDateTime.now());
            item.setDeliveryStatus(TicketRecycleDeliveryEnum.CONFIRM.getCode());

            swTkTicketDeliveryDetailService.updateBatchById(overTimeDetailList);
        });
        return R.ok(swTkTicketDeliveryService.updateBatchById(overTimeList));
    }
    /**
     * 车票配送信息模板下载
     * @param
     * @return
     * @throws
     */
    @ApiOperation(value = "车票配送信息模板下载", notes = "车票配送信息模板下载")
    @GetMapping("/exportTamplateDelivery")
    public void exportTamplateDelivery(HttpServletResponse response) {
        swTkTicketDeliveryService.exportTamplateDelivery(response);
    }
    /**
     * 车票配送信息导入
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "车票配送信息导入", notes = "车票配送信息导入")
    @SysLog("车票配送信息导入")
    @PostMapping({ "/ImportDelivery" })
    @Transactional(rollbackFor = Exception.class)
    public R ImportDelivery(@RequestParam("file") final MultipartFile file) throws Exception {

        final File excelFile = MultipartFileToFile.multipartFileToFile(file);
        List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet().headRowNumber(2).doReadSync();
        if (CollectionUtil.isNotEmpty(listMap)) {
            MultipartFileToFile.delteTempFile(excelFile);
            List<SwTkTicketDeliveryAndDetailExcelDvo> excelDvoList = new ArrayList<>();//处理数据表
            List<SwTkTicketDeliveryDetail> swTkTicketDeliveryDetailList = new ArrayList<>();//配送明细表

            for (int m = 0; m < listMap.size(); m++) {
                Map<Integer, String> data = listMap.get(m);
                // 返回每条数据的键值对 key表示所在的列位置 value表示所在列的值
                LOGGER.info("读取到数据:{}", JSON.toJSONString(data));
                SwTkTicketDeliveryAndDetailExcelDvo excelDvo = new SwTkTicketDeliveryAndDetailExcelDvo();
                if(ObjectUtil.isEmpty(data.get(0))){
                    return R.failed("导入失败，请检查【线路】后重新导入！");
                }else {
                    SwParamLine swParamLine = swParamLineMapper.selectOne(Wrappers.<SwParamLine>lambdaQuery().eq(SwParamLine::getName, data.get(0)));
                    if(ObjectUtil.isEmpty(swParamLine)){
                        return R.failed("导入失败，请检查【线路】后重新导入！");
                    }
                    excelDvo.setLineCode(swParamLine.getCode());//线路
                }

                if(ObjectUtil.isEmpty(data.get(1))){
                    return R.failed("导入失败，请检查【站点】后重新导入！");
                }else {
                    SwParamStation swParamStation = swParamStationMapper.selectOne(Wrappers.<SwParamStation>lambdaQuery()
                            .eq(SwParamStation::getLineCode, excelDvo.getLineCode()).eq(SwParamStation::getName, data.get(1)));
                    if(ObjectUtil.isEmpty(swParamStation)){
                        return R.failed("导入失败，请检查【站点】后重新导入！");
                    }
                    excelDvo.setStationCode(swParamStation.getCode());//站点
                }


                if(ObjectUtil.isNotEmpty(data.get(7))){
                    SwPmTicketCardType swPmTicketCardType = swPmTicketCardTypeService.getOne(Wrappers.<SwPmTicketCardType>lambdaQuery().eq(SwPmTicketCardType::getMainName, data.get(7)));
                    excelDvo.setTicketType(getStringData(swPmTicketCardType.getMainEnName()));//票种
                }

                if(ObjectUtil.isNotEmpty(data.get(8))){
                    SwPmTicketCardTypeParam swPmTicketCardTypeParam = swPmTicketCardTypeParamService.getOne(Wrappers.<SwPmTicketCardTypeParam>lambdaQuery()
                            .eq(SwPmTicketCardTypeParam::getSubName,data.get(8)));
                    excelDvo.setTicketTypeParam(getStringData(swPmTicketCardTypeParam.getSubEnName()));//车票名称
                }
                if(ObjectUtil.isEmpty(data.get(6))){
                    return R.failed("导入失败，请检查【时间格式】后重新导入！");
                }
                excelDvo.setDeliveryTime(data.get(6));//配送时间

                excelDvo.setDeliveryPersonName(getStringData(data.get(2)));//配送人1
                excelDvo.setDeliveryPersonCode(getStringData(data.get(3)));//配送人工号1
                excelDvo.setDeliveryPersonTwoName(getStringData(data.get(4)));//配送人2
                excelDvo.setDeliveryPersonTwoCode(getStringData(data.get(5)));//配送人工号2

                excelDvo.setNumberInterval(getStringData(data.get(9)));//号段
                excelDvo.setCardNumber(getStringData(data.get(10)));//卡号
                excelDvo.setTicketAmount(getData(data.get(11)));//金额
                excelDvo.setTicketCount(getStringData(data.get(12)));//次数
                excelDvo.setDeliveryCount(data.get(13) == null ? 0 : Integer.valueOf(data.get(13)));//配送/入张数
                excelDvo.setRemark(getStringData(data.get(14)));//备注
                excelDvoList.add(excelDvo);

            }
            // 分组统计配送车票
            Map<String,List<SwTkTicketDeliveryAndDetailExcelDvo>> countMap = excelDvoList.stream().collect(Collectors
                    .groupingBy(o -> o.getLineCode() + "_" + o.getStationCode()
                            + "_" + o.getDeliveryPersonCode() + "_" + o.getDeliveryPersonName()
                            + "_" + o.getDeliveryPersonTwoCode() + "_" + o.getDeliveryPersonTwoName()
                            + "_" +o.getDeliveryTime(), Collectors.toList()));
            if(countMap.isEmpty()){
                return R.failed("导入失败，请检查数据后重新导入！");
            }
            Set<String> keySet = countMap.keySet();
            PigxUser user = SecurityUtils.getUser();
            for (String key : keySet) {
                List<SwTkTicketDeliveryAndDetailExcelDvo> dvos = countMap.get(key);
                String[] temp = key.split("_");
                String lineCode = temp[0];
                String stationCode = temp[1];
                String deliveryPersonCode = temp[2];
                String deliveryPersonName = temp[3];
                String deliveryPersonTwoCode = temp[4];
                String deliveryPersonTwoName = temp[5];
                String deliveryTime = temp[6];
                SwTkTicketDelivery swTkTicketDelivery = new SwTkTicketDelivery();//配送主表
                swTkTicketDelivery.setLineCode(lineCode);
                swTkTicketDelivery.setStationCode(stationCode);
                swTkTicketDelivery.setDeliveryPersonCode(deliveryPersonCode);
                swTkTicketDelivery.setDeliveryPersonName(deliveryPersonName);
                swTkTicketDelivery.setDeliveryPersonTwoCode(deliveryPersonTwoCode);
                swTkTicketDelivery.setDeliveryPersonTwoName(deliveryPersonTwoName);
                swTkTicketDelivery.setDeliveryTime(DateUtilsSt.LocalDateTimeToString(deliveryTime));
                List<SwTkTicketDelivery> one = swTkTicketDeliveryService.list(Wrappers.query(swTkTicketDelivery));
                swTkTicketDelivery.setDataSource("0");//人工添加
                swTkTicketDelivery.setNoticeStatus("0");//通知状态
                swTkTicketDelivery.setDeliveryStatus("0");//确认状态
                int sum = dvos.stream().mapToInt(SwTkTicketDeliveryAndDetailExcelDvo::getDeliveryCount).sum();
                swTkTicketDelivery.setDeliveryCount(sum);//配送数量
				swTkTicketDelivery.setImportFlag("1");//导入数据标识  20240611增加
                swTkTicketDelivery.setDelFlag("0");
                swTkTicketDelivery.setDeptId(user.getDeptId());
                swTkTicketDelivery.setCreatorId(user.getId());
                swTkTicketDelivery.setCreatorName(user.getNikeName());//导入人
                swTkTicketDelivery.setCreateTime(LocalDateTime.now());
                if(CollectionUtils.isEmpty(one)){
                    swTkTicketDeliveryService.save(swTkTicketDelivery);
                    dvos.forEach(x -> {
                        SwTkTicketDeliveryDetail swTkTicketDeliveryDetail = new SwTkTicketDeliveryDetail();//配送明细表
                        BeanUtils.copyProperties(x,swTkTicketDeliveryDetail);
                        swTkTicketDeliveryDetail.setRefId(swTkTicketDelivery.getId());//主表关联id
                        swTkTicketDeliveryDetail.setDelFlag("0");
                        swTkTicketDeliveryDetailList.add(swTkTicketDeliveryDetail);
                    });
                }else {
                    continue;
                }
            }
            if(CollectionUtil.isNotEmpty(swTkTicketDeliveryDetailList)){
                swTkTicketDeliveryDetailService.saveBatch(swTkTicketDeliveryDetailList);
            }
        }
        return R.ok();
    }

    private BigDecimal getData(String money){
        try {
            BigDecimal itemMoney = new BigDecimal(money).setScale(2, BigDecimal.ROUND_HALF_UP);
            return itemMoney;
        } catch (Exception e) {
            return new  BigDecimal("0.00");
        }

    }
    private String getStringData(String param){
        if(ObjectUtil.isEmpty(param)){
            return "";
        }
        return param;
    }
}
